<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :minHeight="100"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <a-select
      ref="select"
      mode="multiple"
      v-model:value="roles"
      style="width: 100%"
      :options="roleList"
    >
      <!-- <a-select-option value="jack">Jack</a-select-option>
      <a-select-option value="lucy">Lucy</a-select-option>
      <a-select-option value="disabled" disabled>Disabled</a-select-option>
      <a-select-option value="Yiminghe">yiminghe</a-select-option> -->
    </a-select>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  // import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  // import { postUsers, putUsers } from '/@/api/sys/user';
  // const { createMessage } = useMessage();
  import { bindUserRoles, getRoleList, getUserRole, RoleItem } from '/@/api/sys/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { useUserStoreWithOut } from '/@/store/modules/user';
  import { Select } from 'ant-design-vue';

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, 'a-select': Select },
    emits: ['success', 'register'],
    setup(_) {
      const isUpdate = ref(true);
      let userId = 0;
      // let oldUserName: string;
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        console.log(data);
        userId = data.data.id;
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        fetchConfig();
        if (unref(isUpdate)) {
          // oldUserName = data.record.username;
        }
      });

      // const userStore = useUserStoreWithOut();

      const getTitle = computed(() => '用户角色配置');
      const { createMessage } = useMessage();
      async function handleSubmit() {
        // console.log(userId, roles);
        bindUserRoles({
          user_id: userId,
          role_ids: roles.value.map((v) => v),
        }).then(() => {
          closeModal();
          createMessage.success('配置成功！');
        });
      }

      const roles = ref<number[]>([]);
      const roleList = ref<RoleItem[]>([]);

      function fetchConfig() {
        getUserRole(userId).then((res) => {
          roles.value = res.map((v) => (v as any).role_id);
        });
      }
      getRoleList().then((res) => {
        roleList.value = res.map((v) => ({ ...v, label: v.name, value: v.id }));
      });

      return { registerModal, getTitle, handleSubmit, roles, roleList };
    },
  });
</script>
